<template>
    <div
        class="quote-analysis-system h-screen flex flex-col overflow-hidden bg-gray-50 text-gray-900"
    >
        <!-- 主内容区 -->
        <el-main class="flex-1 flex overflow-hidden p-0">
            <!-- 左侧文件列表区域 - 优化后：层级简化、响应式适配 -->
            <section
                class="file-list-container bg-white border-r border-gray-200 flex flex-col h-full transition-all duration-300 ease-in-out"
                :class="{
                    'w-full md:w-1/3': showFileList,
                    'w-0 md:w-0': !showFileList,
                    'hidden md:flex': isMobile && !showFileList, // 移动端隐藏时完全不占空间
                }"
            >
                <!-- 左侧工具栏 - 优化：紧凑布局、功能分区 -->
                <div
                    class="file-list-header p-3 border-b border-gray-200 flex flex-wrap items-center justify-between gap-2"
                >
                    <div class="flex items-center gap-3">
                        <el-icon @click="handleBack" style="cursor: pointer"
                            ><ArrowLeftBold
                        /></el-icon>
                        <h1 class="text-lg font-semibold">报价文件列表</h1>
                    </div>

                    <div class="flex items-center gap-2">
                        <!-- 上传按钮 - 优化：图标前置，视觉更聚焦 -->
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleUpload"
                        >
                            <el-icon class="el-icon--left"><Upload /></el-icon>
                            上传文件
                        </el-button>

                        <!-- 删除按钮 - 优化：禁用状态更明显 -->
                        <el-button
                            type="text"
                            size="small"
                            icon="DeleteFilled"
                            class="border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors"
                            :disabled="selectedFileIds.length === 0"
                            :class="{
                                'opacity-50 cursor-not-allowed':
                                    selectedFileIds.length === 0,
                            }"
                            @click="handleDeleteSelected"
                        >
                            <span class="hidden sm:inline">删除</span>
                        </el-button>

                        <!-- 移动端关闭按钮 - 优化：仅在移动端显示 -->
                        <el-button
                            type="text"
                            size="small"
                            icon="el-icon-close"
                            class="md:hidden text-gray-500 hover:text-gray-800"
                            @click="showFileList = false"
                            v-if="isMobile"
                        ></el-button>
                    </div>
                </div>

                <!-- 文件列表内容区 - 优化：滚动流畅度、空状态友好 -->
                <div
                    class="file-list-content flex-1 overflow-y-auto p-3 space-y-2"
                >
                    <!-- 空状态 - 优化：视觉更柔和，引导明确 -->
                    <div
                        v-if="fileList.length === 0"
                        class="empty-state h-full flex flex-col items-center justify-center p-6 text-gray-500"
                    >
                        <Document size="48" class="opacity-30 mb-4" />
                        <p class="text-base font-medium mb-2">暂无文件</p>
                        <p
                            class="text-sm text-gray-400 mb-4 text-center max-w-xs"
                        >
                            支持 PDF、Word、Excel、CSV、TXT 格式
                        </p>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleUpload"
                        >
                            <el-icon class="el-icon--left"><Upload /></el-icon>
                            上传文件
                        </el-button>
                    </div>

                    <!-- 文件列表 - 优化：复选框组层级简化，卡片交互增强 -->
                    <el-checkbox-group
                        v-model="selectedFileIds"
                        class="file-list-grid space-y-2"
                        v-else
                    >
                        <div
                            v-for="file in fileList"
                            :key="file.id"
                            class="file-card flex items-center justify-between p-3 border rounded-lg cursor-pointer transition-all duration-200 hover:shadow-sm"
                            :class="{
                                'border-primary bg-primary/5':
                                    selectedFileIds.includes(file.id),
                                'border-gray-200 bg-white':
                                    !selectedFileIds.includes(file.id),
                            }"
                            @click="handleFileClick(file)"
                        >
                            <!-- 复选框 - 优化：与卡片对齐，点击不触发卡片选中 -->
                            <el-checkbox
                                :label="file.id"
                                class="mr-3 flex-shrink-0"
                                @click.stop
                                size="small"
                            />

                            <!-- 文件信息区 - 优化：flex布局，空间分配合理 -->
                            <div
                                class="file-info flex items-center flex-1 min-w-0"
                            >
                                <!-- 文件图标 - 优化：尺寸统一，颜色区分明确 -->
                                <el-icon
                                    size="20"
                                    class="mr-3 flex-shrink-0"
                                    :class="getFileIconClass(file.extension)"
                                >
                                    <Document />
                                </el-icon>

                                <!-- 文件名称与详情 - 优化：名称优先显示，超出省略 -->
                                <div class="file-meta min-w-0">
                                    <h3
                                        class="file-name text-sm font-medium text-gray-800 truncate"
                                        :title="file.name"
                                    >
                                        {{ file.name }}
                                    </h3>
                                    <p
                                        class="file-detail text-xs text-gray-500 mt-0.5"
                                    >
                                        {{ formatFileSize(file.size) }} ·
                                        {{ file.uploadDate }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </el-checkbox-group>
                </div>

                <!-- 左侧状态栏 - 优化：信息简洁，固定底部 -->
                <div
                    class="file-list-footer p-3 border-t border-gray-200 text-xs text-gray-500 flex justify-between"
                >
                    <span>共 {{ fileList.length }} 个文件</span>
                    <span>总计: {{ formatFileSize(totalFileSize) }}</span>
                </div>
            </section>

            <!-- 右侧解析结果区域 - 优化：移动端添加返回按钮 -->
            <section
                class="flex-1 bg-white flex flex-col h-full overflow-hidden"
            >
                <!-- 右侧工具栏 - 新增：移动端返回按钮 -->
                <div
                    class="p-3 border-b border-gray-200 flex flex-wrap gap-2 items-center justify-between"
                >
                    <div class="flex items-center">
                        <!-- 移动端返回按钮 - 仅在隐藏左侧列表时显示 -->
                        <el-button
                            type="text"
                            size="small"
                            icon="ArrowLeftFilled"
                            class="md:hidden mr-2 text-gray-500 hover:text-gray-800"
                            @click="showFileList = true"
                            v-if="isMobile && !showFileList"
                        ></el-button>
                        <h2 class="text-lg font-medium">解析结果</h2>
                    </div>

                    <!-- 右侧操作按钮 - 保持原有逻辑 -->
                    <div class="flex gap-2">
                        <el-button
                            type="primary"
                            icon="MagicStick"
                            size="small"
                            class="flex items-center"
                            :disabled="selectedFileIds.length === 0"
                            @click="handleBulkParse"
                        >
                            <span>解析选中文件</span>
                        </el-button>
                        <el-button
                            icon="SuccessFilled"
                            type="default"
                            size="small"
                            class="flex items-center"
                            :disabled="!parsedResult"
                            @click="handleSaveResult"
                        >
                            保存结果
                        </el-button>
                        <el-button
                            icon="Download"
                            type="default"
                            size="small"
                            class="flex items-center"
                            :disabled="!parsedResult"
                            @click="handleDownloadResult"
                        >
                            下载结果
                        </el-button>
                        <el-button
                            icon="view"
                            type="default"
                            size="small"
                            class="flex items-center"
                            :disabled="selectedFileIds.length === 0"
                        >
                            预览文件
                        </el-button>
                    </div>
                </div>
                <!-- 解析结果内容区 -->
                <div class="flex-1 overflow-y-auto p-6">
                    <!-- 未选择文件状态 -->
                    <el-empty
                        description="请从左侧选择一个文件进行解析"
                        class="h-full flex flex-col items-center justify-center text-gray-400"
                        v-if="selectedFileIds.length === 0 && !parsedResult"
                    >
                        <template #image>
                            <ArrowLeft class="opacity-30 text-xl" />
                        </template>
                    </el-empty>

                    <!-- 解析中状态 -->
                    <div
                        class="h-full flex flex-col items-center justify-center text-gray-500"
                        v-else-if="isParsing"
                    >
                        <el-loading-spinner
                            class="mb-4 text-primary"
                        ></el-loading-spinner>
                        <p>正在解析文件，请稍候...</p>
                    </div>

                    <!-- 解析错误状态 -->
                    <div
                        class="h-full flex flex-col items-center justify-center text-gray-500"
                        v-else-if="parseError"
                    >
                        <WarningFilled class="mb-4 text-danger text-xl" />
                        <p class="text-lg font-medium text-danger mb-2">
                            解析失败
                        </p>
                        <p class="text-center max-w-md mb-6 text-gray-500">
                            {{
                                errorMessage ||
                                "文件格式不支持或内容无法识别，请检查文件后重试"
                            }}
                        </p>
                        <el-button type="primary" @click="retryParse"
                            >重新解析</el-button
                        >
                    </div>

                    <!-- 解析结果展示区 -->
                    <div v-else-if="parsedResult">
                        <!-- 文件信息 -->
                        <el-card
                            shadow="hover"
                            class="mb-6"
                            style="background-color: #f5f7fa"
                        >
                            <div
                                class="flex flex-col md:flex-row items-start md:items-center justify-between"
                            >
                                <div class="flex items-center mb-3 md:mb-0">
                                    <el-icon
                                        size="25"
                                        :class="
                                            getFileIconColor(
                                                selectedFile?.extension || ''
                                            )
                                        "
                                        class="mr-2 ml-2"
                                    >
                                        <Document />
                                    </el-icon>
                                    <div>
                                        <h3 class="text-lg font-medium">
                                            {{ selectedFile?.name || "" }}
                                        </h3>
                                        <p class="text-sm text-gray-500">
                                            解析于 {{ parsedResult.parseTime }}
                                        </p>
                                    </div>
                                </div>
                                <el-tag
                                    type="success"
                                    class="flex items-center"
                                >
                                    <el-icon><SuccessFilled /></el-icon>
                                    解析成功
                                </el-tag>
                            </div>
                        </el-card>

                        <!-- 报价总览和税费信息 -->
                        <div class="mb-6">
                            <h3
                                class="text-lg font-semibold mb-4 flex items-center"
                            >
                                <el-icon color="blue" class="mr-2"
                                    ><DataBoard
                                /></el-icon>
                                报价总览
                            </h3>

                            <el-row :gutter="20" class="mb-6">
                                <el-col :xs="12" :lg="6">
                                    <el-card shadow="hover" class="h-full">
                                        <p class="text-sm text-gray-500 mb-1">
                                            供应商
                                        </p>
                                        <p class="text-xl font-semibold">
                                            {{ parsedResult.supplier }}
                                        </p>
                                    </el-card>
                                </el-col>
                                <el-col :xs="12" :lg="6">
                                    <el-card shadow="hover" class="h-full">
                                        <p class="text-sm text-gray-500 mb-1">
                                            含税总价
                                        </p>
                                        <p
                                            class="text-xl font-semibold text-danger"
                                        >
                                            {{
                                                formatCurrency(
                                                    parsedResult.totalPriceWithTax
                                                )
                                            }}
                                        </p>
                                    </el-card>
                                </el-col>
                                <el-col :xs="12" :lg="6">
                                    <el-card shadow="hover" class="h-full">
                                        <p class="text-sm text-gray-500 mb-1">
                                            不含税总价
                                        </p>
                                        <p class="text-xl font-semibold">
                                            {{
                                                formatCurrency(
                                                    parsedResult.totalPriceWithoutTax
                                                )
                                            }}
                                        </p>
                                    </el-card>
                                </el-col>
                                <el-col :xs="12" :lg="6">
                                    <el-card shadow="hover" class="h-full">
                                        <p class="text-sm text-gray-500 mb-1">
                                            税率
                                        </p>
                                        <p
                                            class="text-xl font-semibold text-primary"
                                        >
                                            {{ parsedResult.taxRate }}%
                                        </p>
                                    </el-card>
                                </el-col>
                            </el-row>

                            <!-- 税金信息 -->
                            <el-card shadow="hover" class="mb-6">
                                <div
                                    class="flex flex-col md:flex-row items-start md:items-center justify-between"
                                >
                                    <div class="mb-3 md:mb-0">
                                        <h4 class="font-medium">
                                            税金计算方式
                                        </h4>
                                        <p class="text-sm text-gray-500 mt-1">
                                            税金是否单独计算：{{
                                                parsedResult.taxCalculationSeparate
                                                    ? "是"
                                                    : "否"
                                            }}
                                        </p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-sm text-gray-500">
                                            合计税额
                                        </p>
                                        <p
                                            class="text-lg font-semibold text-primary"
                                        >
                                            {{
                                                formatCurrency(
                                                    parsedResult.totalTax
                                                )
                                            }}
                                        </p>
                                    </div>
                                </div>
                            </el-card>

                            <!-- 分部分项报价 -->
                            <div>
                                <h3
                                    class="text-lg font-semibold mb-4 flex items-center"
                                >
                                    <el-icon class="mr-2" color="blue"
                                        ><List
                                    /></el-icon>
                                    分部分项报价
                                </h3>

                                <!-- 单项工程 -->
                                <div
                                    v-for="(
                                        project, projectIndex
                                    ) in parsedResult.projects"
                                    :key="projectIndex"
                                >
                                    <el-collapse
                                        v-model="activeProjectNames"
                                        :accordion="true"
                                    >
                                        <el-collapse-item
                                            :title="`单项工程：${project.name}`"
                                            :name="`project-${projectIndex}`"
                                            class="border border-gray-200 rounded-t-lg overflow-hidden"
                                        >
                                            <template #header>
                                                <div
                                                    class="bg-primary/10 flex items-center"
                                                >
                                                    <span class="flex-1">{{
                                                        `单项工程：${project.name}`
                                                    }}</span>
                                                </div>
                                            </template>

                                            <!-- 单位工程 -->
                                            <el-collapse
                                                v-model="
                                                    activeUnitNames[
                                                        projectIndex
                                                    ]
                                                "
                                                :accordion="true"
                                            >
                                                <el-collapse-item
                                                    :title="`单位工程：${unit.name}`"
                                                    :name="`unit-${projectIndex}-${unitIndex}`"
                                                    class="border-x border-gray-200 border-t-0"
                                                    v-for="(
                                                        unit, unitIndex
                                                    ) in project.units"
                                                    :key="unitIndex"
                                                >
                                                    <template #header>
                                                        <div
                                                            class="bg-gray-50 pl-8 flex items-center"
                                                        >
                                                            <span
                                                                class="flex-1"
                                                                >{{
                                                                    `单位工程：${unit.name}`
                                                                }}</span
                                                            >
                                                        </div>
                                                    </template>

                                                    <!-- 分部分项 -->
                                                    <el-collapse
                                                        v-model="
                                                            activeSectionNames[
                                                                projectIndex
                                                            ][unitIndex]
                                                        "
                                                        :accordion="true"
                                                    >
                                                        <el-collapse-item
                                                            :title="`分部分项：${section.name}`"
                                                            :name="`section-${projectIndex}-${unitIndex}-${sectionIndex}`"
                                                            class="border-x border-gray-200 border-t-0"
                                                            v-for="(
                                                                section,
                                                                sectionIndex
                                                            ) in unit.sections"
                                                            :key="sectionIndex"
                                                        >
                                                            <template #header>
                                                                <div
                                                                    class="bg-white pl-12 flex items-center"
                                                                >
                                                                    <span
                                                                        class="flex-1"
                                                                        >{{
                                                                            `分部分项：${section.name}`
                                                                        }}</span
                                                                    >
                                                                </div>
                                                            </template>

                                                            <!-- 清单项目表格 -->
                                                            <div
                                                                class="p-2 border-x border-gray-200"
                                                            >
                                                                <el-table
                                                                    :data="
                                                                        section.items
                                                                    "
                                                                    border
                                                                    size="small"
                                                                    class="mb-2"
                                                                >
                                                                    <el-table-column
                                                                        prop="code"
                                                                        label="编码"
                                                                        width="100"
                                                                        align="left"
                                                                    ></el-table-column>
                                                                    <el-table-column
                                                                        prop="name"
                                                                        label="名称"
                                                                        align="left"
                                                                    ></el-table-column>
                                                                    <el-table-column
                                                                        prop="description"
                                                                        label="项目特征描述"
                                                                        align="left"
                                                                    ></el-table-column>
                                                                    <el-table-column
                                                                        prop="unit"
                                                                        label="计量单位"
                                                                        width="100"
                                                                        align="left"
                                                                    ></el-table-column>
                                                                    <el-table-column
                                                                        prop="quantity"
                                                                        label="工程量"
                                                                        width="100"
                                                                        align="right"
                                                                    ></el-table-column>
                                                                    <el-table-column
                                                                        prop="unitPrice"
                                                                        label="综合单价(元)"
                                                                        width="130"
                                                                        align="right"
                                                                    ></el-table-column>
                                                                    <!-- 修复：合价列 - 同样绑定函数引用 -->
                                                                    <el-table-column
                                                                        prop="totalPrice"
                                                                        label="合价(元)"
                                                                        width="110"
                                                                        align="right"
                                                                        cell-class-name="font-medium"
                                                                    ></el-table-column>
                                                                </el-table>

                                                                <!-- 本分项合计 -->
                                                                <div
                                                                    class="flex justify-end bg-gray-50 p-2 rounded"
                                                                >
                                                                    <div
                                                                        class="text-right"
                                                                    >
                                                                        <span
                                                                            class="font-medium mr-4"
                                                                            >本分项合计</span
                                                                        >
                                                                        <span
                                                                            class="font-semibold text-danger"
                                                                            >{{
                                                                                formatCurrency(
                                                                                    section.total
                                                                                )
                                                                            }}</span
                                                                        >
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </el-collapse-item>
                                                    </el-collapse>
                                                </el-collapse-item>
                                            </el-collapse>
                                        </el-collapse-item>
                                    </el-collapse>
                                </div>

                                <!-- 报价汇总信息 -->
                                <el-card shadow="hover" class="mt-6">
                                    <el-row :gutter="20">
                                        <el-col :xs="24" :md="12">
                                            <h4
                                                class="text-sm font-medium text-gray-500 mb-2"
                                            >
                                                价格构成
                                            </h4>
                                            <el-descriptions :column="1">
                                                <el-descriptions-item
                                                    label="分部分项工程费"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult
                                                                .priceComponents
                                                                .subtotal
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                                <el-descriptions-item
                                                    label="措施项目费"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult
                                                                .priceComponents
                                                                .measures
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                                <el-descriptions-item
                                                    label="其他项目费"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult
                                                                .priceComponents
                                                                .other
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                                <el-descriptions-item
                                                    label="规费"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult
                                                                .priceComponents
                                                                .fees
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                                <el-descriptions-item
                                                    label="税金(9%)"
                                                    label-class-name="text-primary"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult.totalTax
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                            </el-descriptions>
                                        </el-col>
                                        <el-col :xs="24" :md="12">
                                            <h4
                                                class="text-sm font-medium text-gray-500 mb-2"
                                            >
                                                报价总计
                                            </h4>
                                            <el-descriptions :column="1">
                                                <el-descriptions-item
                                                    label="不含税总价"
                                                    >{{
                                                        formatCurrency(
                                                            parsedResult.totalPriceWithoutTax
                                                        )
                                                    }}</el-descriptions-item
                                                >
                                                <el-descriptions-item
                                                    label="含税总价"
                                                    label-class-name="text-danger"
                                                >
                                                    <span
                                                        class="text-lg font-bold"
                                                        >{{
                                                            formatCurrency(
                                                                parsedResult.totalPriceWithTax
                                                            )
                                                        }}</span
                                                    >
                                                </el-descriptions-item>
                                                <el-descriptions-item
                                                    label="报价有效期"
                                                    label-class-name="text-gray-400"
                                                >
                                                    <span
                                                        class="text-xs text-gray-500"
                                                        >{{
                                                            parsedResult.validityPeriod
                                                        }}</span
                                                    >
                                                </el-descriptions-item>
                                            </el-descriptions>
                                        </el-col>
                                    </el-row>
                                </el-card>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </el-main>

        <!-- 上传文件进度条 -->
        <el-progress
            v-if="showUploadProgress"
            :percentage="uploadProgress"
            :status="uploadProgress === 100 ? 'success' : 'progress'"
            class="upload-progress fixed bottom-4 left-4 right-4 max-w-md mx-auto bg-white p-3 rounded-lg shadow-md border border-gray-200 z-50"
            stroke-width="6"
        >
            <template #default>
                <div
                    class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-1"
                >
                    <div>
                        <div class="font-medium text-sm">正在上传</div>
                        <div
                            class="text-xs text-gray-500 truncate max-w-[200px]"
                        >
                            {{ uploadFileName }}
                        </div>
                    </div>
                    <div class="text-xs text-gray-500">
                        {{ formatFileSize(uploadedSize) }} /
                        {{ formatFileSize(totalUploadSize) }}
                    </div>
                </div>
            </template>
        </el-progress>

        <!-- 上传弹框 -->
        <el-dialog v-model="filesUpload" width="80vw">
            <DocumentUpload />
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessageBox, ElNotification, ElMessage } from "element-plus";
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import DocumentUpload from "./documentUpload.vue";
import { useRouter } from "vue-router";
const router = useRouter();
// -------------------------- 状态管理 - 优化：精简冗余状态 --------------------------
// 文件列表数据
const fileList = ref([
    {
        id: 1,
        name: "2023年Q3供应商报价单.pdf",
        extension: "pdf",
        size: 2400000,
        uploadDate: "2023-09-01",
    },
    {
        id: 2,
        name: "电子元件报价表.xlsx",
        extension: "xlsx",
        size: 1800000,
        uploadDate: "2023-08-28",
    },
    {
        id: 3,
        name: "建筑工程报价单.docx",
        extension: "docx",
        size: 985000,
        uploadDate: "2023-08-25",
    },
]);

// 选中文件ID数组（核心状态，管理多选/单选）
const selectedFileIds = ref([3]);
const filesUpload = ref(false);
// 当前选中文件（计算属性，避免冗余状态）
const selectedFile = computed(() => {
    return selectedFileIds.value.length > 0
        ? fileList.value.find((file) => file.id === selectedFileIds.value[0]) ||
              null
        : null;
});

// 解析相关状态
const isParsing = ref(false);
const parseError = ref(false);
const errorMessage = ref("");
const parsedResult = ref(null);

// 上传进度状态
const showUploadProgress = ref(false);
const uploadProgress = ref(0);
const uploadFileName = ref("");
const uploadedSize = ref(0);
const totalUploadSize = ref(0);

// 响应式布局状态
const isMobile = ref(false);
const showFileList = ref(true);

// 总文件大小（计算属性，实时更新）
const totalFileSize = computed(() => {
    return fileList.value.reduce((total, file) => total + file.size, 0);
});

// 折叠面板状态（保持原有逻辑）
const activeProjectNames = ref(["project-0"]);
const activeUnitNames = ref([["unit-0-0"]]);
const activeSectionNames = ref([[["section-0-0-0"]]]);

// -------------------------- 生命周期 - 优化：添加卸载钩子 --------------------------
onMounted(() => {
    // 关键：用 nextTick 确保 DOM 已挂载
    nextTick(() => {
        checkScreenSize();
        // 事件监听中也包裹 nextTick
        window.addEventListener("resize", () => {
            nextTick(checkScreenSize);
        });
        if (selectedFile.value) fetchParsedResult();
    });
});

onUnmounted(() => {
    // 移除事件监听，避免内存泄漏
    window.removeEventListener("resize", checkScreenSize);
});

// -------------------------- 工具函数 - 优化：分类清晰，职责单一 --------------------------
/**
 * 检测屏幕尺寸，更新移动端状态
 */
const checkScreenSize = () => {
    const newIsMobile = window.innerWidth < 768;
    isMobile.value = newIsMobile;
    // 安全获取 DOM 元素：先判断是否存在，再操作样式
    const rightSection = document.querySelector(
        ".quote-analysis-system section:last-child"
    );
    if (!rightSection) return; // 关键：元素不存在时直接返回，避免后续报错

    if (newIsMobile) {
        showFileList.value = selectedFileIds.value.length === 0;
        rightSection.style.minWidth = "100vw";
    } else {
        showFileList.value = true;
        rightSection.style.minWidth = "auto";
    }
};

/**
 * 获取文件图标样式（按扩展名区分）
 * @param {string} extension - 文件扩展名
 * @returns {string} 图标CSS类名
 */
const getFileIconClass = (extension) => {
    if (!extension) return "text-gray-400";
    switch (extension.toLowerCase()) {
        case "pdf":
            return "text-danger";
        case "docx":
        case "doc":
            return "text-blue-600";
        case "xlsx":
        case "xls":
            return "text-success";
        case "txt":
        case "csv":
            return "text-gray-600";
        default:
            return "text-gray-400";
    }
};

/**
 * 格式化文件大小（B -> KB/MB/GB）
 * @param {number} bytes - 文件大小（字节）
 * @returns {string} 格式化后的大小字符串
 */
const formatFileSize = (bytes) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};

/**
 * 格式化货币（保留2位小数，添加千分位）- 增强容错
 * @param {number} value - 金额数值（确保为Number类型）
 * @returns {string} 格式化后的货币字符串
 */
const formatCurrency = (value) => {
    // 新增：类型判断，非数字时返回空字符串或提示
    if (value === undefined || value === null || typeof value !== "number") {
        return "-"; // 或返回空字符串 ""，避免显示 [object Object]
    }
    return `¥ ${value.toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    })}`;
};

/**
 * 显示通知消息（函数式调用，统一样式）
 * @param {string} title - 通知标题
 * @param {string} message - 通知内容
 * @param {string} type - 通知类型（success/error/info/warning）
 */
const showNotificationMessage = (title, message, type = "success") => {
    ElNotification({
        title,
        message,
        type,
        duration: 3000,
        position: "top-right",
        customClass: "app-notification",
        offset: 10,
    });
};
// 按钮事件（可根据实际需求扩展）
const handleBack = () => {
    ElMessage.info("返回上一页");
    router.back();
    // 实际项目中可使用vue-router的back()
};

/**
 * 处理文件点击（选中文件，切换列表显示状态）
 * @param {Object} file - 点击的文件对象
 */
const handleFileClick = (file) => {
    if (isMobile.value) {
        showFileList.value = false;
        // 延迟修改右侧区域样式，确保 DOM 已更新
        nextTick(() => {
            const rightSection = document.querySelector(
                ".quote-analysis-system section:last-child"
            );
            if (rightSection) rightSection.style.minWidth = "100vw";
        });
    }
    selectedFileIds.value = [file.id];
    if (!parsedResult.value || parsedResult.value.fileId !== file.id) {
        fetchParsedResult(file);
    }
};

/**
 * 处理选中文件删除（批量删除，二次确认）
 */
const handleDeleteSelected = () => {
    if (selectedFileIds.value.length === 0) return;
    ElMessageBox.confirm(
        `确定删除选中的 ${selectedFileIds.value.length} 个文件？删除后不可恢复`,
        "确认删除",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
        }
    )
        .then(() => {
            // 过滤掉被删除的文件
            fileList.value = fileList.value.filter(
                (file) => !selectedFileIds.value.includes(file.id)
            );
            // 重置选中状态和解析结果
            selectedFileIds.value = [];
            parsedResult.value = null;
            // 显示删除成功通知
            showNotificationMessage(
                "删除成功",
                `已删除 ${selectedFileIds.value.length} 个文件`,
                "success"
            );
        })
        .catch(() => {
            // 取消删除，不做操作
        });
};

/**
 * 处理文件解析（支持单个文件解析）
 * @param {Object} file - 待解析的文件对象
 */
const fetchParsedResult = (file = null) => {
    const targetFile = file || selectedFile.value;
    if (!targetFile) return;

    isParsing.value = true;
    parseError.value = false;
    parsedResult.value = null;

    // 模拟API请求延迟（1.5秒）
    setTimeout(() => {
        const success = Math.random() > 0.1; // 90% 成功率
        if (success) {
            // 生成模拟解析结果
            parsedResult.value = {
                fileId: targetFile.id,
                parseTime: new Date().toLocaleString("zh-CN"),
                supplier: "中建第一建筑工程有限公司",
                totalPriceWithTax: 2568000,
                totalPriceWithoutTax: 2300000,
                taxRate: 9,
                totalTax: 268000,
                taxCalculationSeparate: true,
                validityPeriod: "2023年10月30日前",
                priceComponents: {
                    subtotal: 1850000,
                    measures: 220000,
                    other: 180000,
                    fees: 50000,
                },
                projects: [
                    {
                        name: "商业综合体建设项目",
                        units: [
                            {
                                name: "主体结构工程",
                                sections: [
                                    {
                                        name: "混凝土结构工程",
                                        items: [
                                            {
                                                code: "010501001",
                                                name: "现浇混凝土基础",
                                                description:
                                                    "C30混凝土，垫层100mm厚C15混凝土",
                                                unit: "m³",
                                                quantity: 120.5,
                                                unitPrice: 865.2,
                                                totalPrice: 104256.6,
                                            },
                                            {
                                                code: "010502001",
                                                name: "现浇混凝土柱",
                                                description:
                                                    "C40混凝土，截面尺寸600×600mm",
                                                unit: "m³",
                                                quantity: 85.3,
                                                unitPrice: 980.5,
                                                totalPrice: 83636.65,
                                            },
                                            {
                                                code: "010503001",
                                                name: "现浇混凝土梁",
                                                description:
                                                    "C35混凝土，截面尺寸300×600mm",
                                                unit: "m³",
                                                quantity: 156.8,
                                                unitPrice: 925.3,
                                                totalPrice: 145087.04,
                                            },
                                        ],
                                        total: 332980.29,
                                    },
                                    {
                                        name: "钢筋工程",
                                        items: [
                                            {
                                                code: "010515001",
                                                name: "现浇构件钢筋",
                                                description:
                                                    "HRB400E，直径25mm",
                                                unit: "t",
                                                quantity: 28.5,
                                                unitPrice: 6850.0,
                                                totalPrice: 195225.0,
                                            },
                                            {
                                                code: "010515001",
                                                name: "现浇构件钢筋",
                                                description:
                                                    "HRB400E，直径16mm",
                                                unit: "t",
                                                quantity: 42.3,
                                                unitPrice: 6720.0,
                                                totalPrice: 284256.0,
                                            },
                                        ],
                                        total: 479481.0,
                                    },
                                ],
                            },
                            {
                                name: "装饰装修工程",
                                sections: [
                                    {
                                        name: "墙面装饰工程",
                                        items: [
                                            {
                                                code: "011201001",
                                                name: "墙面一般抹灰",
                                                description:
                                                    "水泥砂浆抹灰，厚度20mm",
                                                unit: "m²",
                                                quantity: 1250.8,
                                                unitPrice: 38.5,
                                                totalPrice: 48155.8,
                                            },
                                            {
                                                code: "011205001",
                                                name: "石材墙面",
                                                description: "花岗岩，干挂",
                                                unit: "m²",
                                                quantity: 850.5,
                                                unitPrice: 380.0,
                                                totalPrice: 323190.0,
                                            },
                                        ],
                                        total: 371345.8,
                                    },
                                ],
                            },
                        ],
                    },
                ],
            };
            isParsing.value = false;
            showNotificationMessage(
                "解析成功",
                `文件 "${targetFile.name}" 解析完成`,
                "success"
            );
        } else {
            // 解析失败处理
            isParsing.value = false;
            parseError.value = true;
            errorMessage.value = "文件格式不支持或内容损坏，建议重新上传文件";
            showNotificationMessage(
                "解析失败",
                `文件 "${targetFile.name}" 无法解析`,
                "error"
            );
        }
    }, 1500);
};

/**
 * 重新解析当前选中文件
 */
const retryParse = () => {
    if (selectedFile.value) fetchParsedResult(selectedFile.value);
};
// 上传文件弹窗
const handleUpload = () => {
    filesUpload.value = true;
};

/**
 * 批量解析选中文件（默认解析第一个）
 */
const handleBulkParse = () => {
    if (selectedFileIds.value.length === 0) return;
    const firstFile = fileList.value.find(
        (file) => file.id === selectedFileIds.value[0]
    );
    if (firstFile) fetchParsedResult(firstFile);
};

/**
 * 保存解析结果（模拟）
 */
const handleSaveResult = () => {
    if (parsedResult.value && selectedFile.value) {
        showNotificationMessage("保存成功", "解析结果已保存到系统", "success");
        // 实际项目中可调用后端接口保存结果
    }
};

/**
 * 下载解析结果（模拟）
 */
const handleDownloadResult = () => {
    if (parsedResult.value && selectedFile.value) {
        showNotificationMessage(
            "下载开始",
            "解析结果Excel文件正在下载",
            "success"
        );
        // 实际项目中可生成Excel并触发下载
    }
};
const getFileIconColor = (extension) => {
    if (!extension) return "text-gray-400"; // 空值容错
    switch (extension.toLowerCase()) {
        case "pdf":
            return "text-danger text-xl";
        case "docx":
        case "doc":
            return "text-blue-600 text-xl";
        case "xlsx":
        case "xls":
        case "csv":
            return "text-success text-xl";
        case "txt":
            return "text-gray-600 text-xl";
        default:
            return "text-gray-400 text-xl";
    }
};
</script>

<style scoped>
/* -------------------------- 基础样式 - 优化：统一变量，减少冗余 -------------------------- */
.quote-analysis-system {
    --el-color-primary: #165dff;
    --el-color-success: #52c41a;
    --el-color-warning: #faad14;
    --el-color-danger: #ff4d4f;
    --el-color-gray-100: #f7f8fa;
    --el-color-gray-200: #e5e6eb;
    --el-color-gray-300: #c9cdd4;
    --el-color-gray-500: #86909c;
    --el-color-gray-800: #1d2129;
    /* height: 100vh; */
    height: calc(100vh - 84px);
    overflow: hidden;
}

/* -------------------------- 左侧文件列表 - 优化：布局紧凑，交互友好 -------------------------- */
.file-list-container {
    z-index: 10;
}

/* 头部工具栏 */
.file-list-header {
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

/* 内容区 */
.file-list-content {
    background-color: var(--el-color-gray-100);
}

/* 空状态 */
.empty-state {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 文件卡片 - 优化：hover效果柔和，选中状态明显 */
.file-card {
    background-color: white;
    border-radius: 6px;
}

.file-card:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
}

/* 文件信息区 */
.file-info {
    overflow: hidden;
}

.file-name {
    line-height: 1.4;
}

.file-detail {
    line-height: 1.2;
}

/* 操作按钮 - 优化：圆形按钮，hover反馈清晰 */
.file-actions .el-button {
    transition: all 0.2s ease;
}

.file-actions .el-button:hover {
    background-color: var(--el-color-primary/10);
    color: var(--el-color-primary);
}

/* 底部状态栏 */
.file-list-footer {
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
}

/* -------------------------- 上传进度条 - 优化：样式柔和，不干扰操作 -------------------------- */
.upload-progress {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* -------------------------- 响应式适配 - 优化：断点清晰，体验一致 -------------------------- */
@media (max-width: 768px) {
    /* 移动端文件列表隐藏时，右侧占满屏幕 */
    .file-list-container.w-0 + section {
        width: 100vw !important;
        flex: none !important;
    }

    /* 移动端文件卡片 */
    .file-card {
        padding: 2.5px 3px;
    }

    .file-name {
        font-size: 12px;
    }

    .file-detail {
        font-size: 11px;
    }

    /* 操作按钮仅显示图标 */
    .file-actions {
        gap: 0;
    }
}

/* -------------------------- 通知样式 - 优化：不遮挡操作区 -------------------------- */
::v-deep .app-notification {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

/* -------------------------- Element 组件样式覆盖 - 优化：减少冲突 -------------------------- */
::v-deep .el-main {
    padding: 0;
    display: flex;
    height: calc(100vh - 60px) !important; /* 假设头部高度为60px */
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
}

::v-deep .el-progress__success-path {
    background-color: var(--el-color-primary);
}

::v-deep .el-tag--success {
    background-color: var(--el-color-success/10);
    color: var(--el-color-success);
    border-color: var(--el-color-success/20);
}
</style>
